package com.raindrop.rd;

import com.raindrop.rd.parser.Parser;
import com.raindrop.rd.parser.ast.Block;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptException;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

/**
 * RD语言编译器，讲源码编译为可执行代码
 *
 * @author BillDowney
 * @date 2021/3/22 15:38
 */
public class RDCompilable implements Compilable {

    private final RDScriptEngine engine;

    public RDCompilable(RDScriptEngine engine) {
        this.engine = engine;
    }

    @Override
    public CompiledScript compile(String script) throws ScriptException {
        Parser parser = new Parser();
        List<Block> blocks = parser.parse(script);
        return new RDCompiledScript(engine, blocks);
    }

    @Override
    public CompiledScript compile(Reader script) throws ScriptException {
        return this.compile(this.readString(script));
    }

    public String readString(Reader reader) {
        StringBuilder builder = new StringBuilder();
        char[] buf = new char[1024];
        int len;
        try {
            while ((len = reader.read(buf, 0, buf.length)) != -1) {
                builder.append(buf, 0, len);
            }
        } catch (IOException ignored) {

        }
        return builder.toString();
    }
}
